package com.af.community.smart.business

import android.os.Bundle
import androidx.lifecycle.Observer
import com.af.community.smart.base.BaseActivity
import com.af.community.smart.base.getString
import com.af.community.smart.base.makeCall
import com.af.community.smart.base.oneClick
import com.af.community.smart.utils.*
import com.af.community.smart.viewmodel.UpdateViewModel
import kotlinx.android.synthetic.main.activity_setting.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class SettingActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)
        initTitle(title = "设置")

        getViewModel().getAboutEvent().observe(
            this,
            Observer {
                val obj = JSONObject(it)
                startActivity<WebActivity>(
                    "type" to "handleList",
                    "title" to obj.optNotNull("title"),
                    "content" to obj.optNotNull("context")
                )
            }
        )
    }

    override fun getViewModel() = getViewModel<UpdateViewModel>()

    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        val tel = getString("servicePhone")

        setting_version.setRightString("v${getVersion()}")
        setting_cache.setRightString(
            GlideCacheUtil.getInstance().getAllCacheSize(baseContext)
        )
        setting_tel.setRightString(tel)

        setting_version.oneClick { getViewModel().checkUpdate(this) }
        setting_cache.oneClick {
            alert(
                message = "确定要清空缓存吗？"
            ) {
                negativeButton("取消") {}
                positiveButton("确定") {
                    GlideCacheUtil.getInstance()
                        .clearImageAllCache(baseContext)
                    setting_cache.setRightString("0B")
                }
            }.show()
        }
        setting_tel.oneClick { if (tel.isNotEmpty()) makeCall(tel) }
        setting_about.oneClick { getViewModel().getAbout() }
        bt_quit.oneClick {
            alert(
                message = "确定要退出当前账号吗？"
            ) {
                negativeButton("取消") {}
                positiveButton("退出") {
                    startActivity<LoginActivity>("offLine" to true)
                }
            }.show()
        }
    }

}
